package com.huacai.comment.service.impl;

import java.util.*;

import com.huacai.common.utils.DateUtils;
import com.huacai.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.huacai.comment.mapper.CommentMapper;
import com.huacai.comment.domain.Comment;
import com.huacai.comment.service.ICommentService;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.util.CollectionUtils;

import static com.huacai.common.utils.SecurityUtils.getUserId;

/**
 *  评论 Service业务层处理
 *
 * @author zou
 * @date 2025-05-26
 */
@Service
public class CommentServiceImpl implements ICommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SqlSessionFactory sqlSessionFactory;

    /**
     * 查询 评论
     *
     * @param commentId 评论 主键
     * @return 评论
     */
    @Override
    public Comment selectCommentByCommentId(String commentId) {
        return commentMapper.selectCommentByCommentId(commentId);
    }

    /**
     * 查询 评论 列表
     *
     * @param comment 评论
     * @return 评论
     */
    @Override
    public List<Comment> selectCommentList(Comment comment) {
        return commentMapper.selectCommentList(comment);
    }

    /**
     * 新增 评论
     *
     * @param comment 评论
     * @return 结果
     */
    @Override
    public int insertComment(Comment comment) {
        comment.setCreateTime(DateUtils.getNowDate());
        comment.setCommentId(IdUtils.randomUUID());
        comment.setUserId(getUserId());
        return commentMapper.insertComment(comment);
    }

    /**
     * 批量新增 评论
     *
     * @param comments 评论 List
     * @return 结果
     */
    @Override
    public int batchInsertComment(List<Comment> comments) {
        SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
        int count = 0;
        if (!CollectionUtils.isEmpty(comments)) {
            try {
                for (int i = 0; i < comments.size(); i++) {
                    int row = commentMapper.insertComment(comments.get(i));
                    // 防止内存溢出，每100次提交一次,并清除缓存
                    boolean bool = (i > 0 && i % 100 == 0) || i == comments.size() - 1;
                    if (bool) {
                        sqlSession.commit();
                        sqlSession.clearCache();
                    }
                    count = i + 1;
                }
            } catch (Exception e) {
                e.printStackTrace();
                // 没有提交的数据可以回滚
                sqlSession.rollback();
            } finally {
                sqlSession.close();
                return count;
            }
        }
        return count;
    }

    /**
     * 修改 评论
     *
     * @param comment 评论
     * @return 结果
     */
    @Override
    public int updateComment(Comment comment) {
        return commentMapper.updateComment(comment);
    }

    /**
     * 批量删除 评论
     *
     * @param commentIds 需要删除的 评论 主键
     * @return 结果
     */
    @Override
    public int deleteCommentByCommentIds(String[] commentIds) {
        return commentMapper.deleteCommentByCommentIds(commentIds);
    }

    /**
     * 删除 评论 信息
     *
     * @param commentId 评论 主键
     * @return 结果
     */
    @Override
    public int deleteCommentByCommentId(String commentId) {
        return commentMapper.deleteCommentByCommentId(commentId);
    }


    public Map<String, Integer> batchSelectCommentCount(List<String> blogIds) {
        if (blogIds == null || blogIds.isEmpty()) {
            return Collections.emptyMap();
        }
        // 每批处理500个ID
        int batchSize = 500;
        Map<String, Integer> finalResult = new HashMap<>();

        // 分批处理
        for (int i = 0; i < blogIds.size(); i += batchSize) {
            int end = Math.min(i + batchSize, blogIds.size());
            List<String> batchIds = blogIds.subList(i, end);

            Map<String, Map<String, Object>> resultMap = commentMapper.batchSelectCommentCount(batchIds);

            resultMap.forEach((blogId, data) ->
                    finalResult.put(blogId, ((Number) data.get("commentCount")).intValue()));
        }

        return finalResult;
    }
}